function addSurgeryService(ticketId) {
	if (validate4AddSurgeryService() == false) {
		return;
	}
	var dt=new Date();
	var hour = dt.getHours()< 10? "0" + dt.getHours(): dt.getHours();
	var min = dt.getMinutes()< 10? "0" + dt.getMinutes(): dt.getMinutes();

	var surgeryDate = $('#inSurgery_yyyy').val() 
	+ '-' 
	+ $('#inSurgery_mm').val()
	+ '-'
	+ $('#inSurgery_dd').val()
	+ ' '
	+ hour + ':' + min + ':00' ;
	
	//var surgeryId = $("select#inputServiceSurgeryList :selected").val();
	var surgeryId = $('#surgeryId').val();

	$.ajax({
		type:		"GET",
		url:	"../InPatientSurgery/AddSurgeryAjax?set_ajax_view",
		data: 	"ticketId=" + ticketId 
		+ "&surgeryDate=" + surgeryDate
		+ "&surgeryServiceId=" + surgeryId
		+ getEmployees() + getRoles() ,		
		dataType:   "json",
		beforeSend: function() {
			showAjaxLoader('reloadInputSurgery', 'innerLoadingInputSurgery', false);
		},
		success: 	function(data) {			
		if (data.error.code == 0) {
			var serviceType = $('#catergoryId').val();
			displayForm4InputService(ticketId, serviceType);

		} else {
			displayError(data.error.mess);				
		}
		showAjaxLoader('reloadInputSurgery', 'innerLoadingInputSurgery', true);
	}
	});	

}
function getEmployees() {
	var employees = '';
	$("table#surgeryParticipants input[name='personNames[]']").each(function () {
		employees += "&employees[]=" + $(this).val();
		
	});
	
	return employees;
}
function getRoles() {
	var roles = '';
	$("table#surgeryParticipants input[name='roles[]']").each(function () {
		roles += "&roles[]=" + $(this).val();
		
	});
	
	return roles;
}

function displaySurgeryTeam(ticketId, surgeryId) {
	
	$.ajax({
		type:		"GET",
		url:	"../InPatientSurgery/DisplaySurgeryTeam?set_ajax_view",
		dataType:   "json",
		data: "ticketId=" + ticketId + "&surgeryId=" + surgeryId,
		success: 	function(data) {			
			if (data.error.code == 0) {
				var buttons = {};
				buttons[_('Close')] = function() {
					$(this).dialog('close');		
				};
				generalDialog('surgeryParticipantsDialog',_("Surgery Participant"),data.result.form,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: false,
					modal: true,
					width:500,
					height:450,
					buttons: buttons
				});
			
			} else {
				displayError(data.error.mess);				
			}
		}
	});	
	
}


function displaySurgeryTeamTemplate() {
	$.ajax({
		type:		"GET",
		url:	"../InPatientSurgery/DisplaySurgeryTeamTemplate?set_ajax_view",
		dataType:   "json",		
		success: 	function(data) {			
			if (data.error.code == 0) {
				$("div#surgeryTeamTemplateDialog").html(data.result.form);
				
				
				var buttons = {};
				buttons[_('Close')] = function() {
					$(this).dialog('close');		
				};
				buttons[_('Save')] = function() {
					if (!validateTempate("msg_viewTemplate")) {
						return false;
					}
					var templateId = $('#current_template_id').val();
					if (templateId <= 0) {		
						return false;
					}
					addNewTemplate('updateTemplateForm');										
				};
				buttons[_('Select')] = function() {
					if (!validateTempate("msg_viewTemplate")) {
						return false;
					}
					var templateId = $('#current_template_id').val();
					var ticketId = $('#currentTicketId').val();
					if (templateId <= 0) {		
						return false;
					}

					$('table#surgeryParticipants tbody').html('');
					var count = 0;
					$('table#templateDetails tbody tr').each(function(){
						count ++;
					});

					for(var i = 0; i < count; i++) {
						if ($('#' + 'template_employee_' + i + ' option:selected').val() != '') {
							var name = $('#' + 'template_employee_' + i + ' option:selected').text();
							var personId = $('#' + 'template_employee_' + i + ' option:selected').val();
							var role = $('#' + 'template_role_' + i + ' option:selected').val();
							var roleName = $('#' + 'template_role_' + i + ' option:selected').text();

							addParticipantFromTemplate(role, roleName, name, personId);
						}
						
					}	

					$(this).dialog('close');		
				};
				generalDialog('surgeryTeamTemplateDialog',_("Surgery Participant"),null,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: false,
					modal: true,
					width:650,
					height:565,
					buttons: buttons
				});
				
				$('#surgeryTeamtabs').tabs({
					select: showTemplate,			
				});
				// get first template
				var firstTemplateId = $('#firstTemplateId').val();
				if (firstTemplateId > 0) {
					getTemplate(firstTemplateId);
					
				}
			
			} else {
				displayError(data.error.mess);				
			}
		}
	});	
	
	
}
function validateTempate(targetId) {
	
	var len = $("select[name='template_role[]']").length;
	var arr = [];
	for(var i=0; i < len; i++){
		var objName	=	$("select[name='template_employee[]']").get(i);
		var objRole	=	$("select[name='template_role[]']").get(i);
		
		if (objName.value != "" && objRole.value != "") {
			if (arr[objName.value + ' ' + objRole.value] == null) {
				arr[objName.value + ' ' + objRole.value] = 1;
			} else {
				showMessage(targetId, _('Duplicated Doctor/Technician and Role'), 'error');
				return false;
			}		
		}
	}
	return true;
}
function addNewTemplate(templateForm) {
	$.ajax({
		type:		"POST",
		url:	'../Surgery/AddNewTemplateAjax?set_ajax_view',
		data: $('#' + templateForm).serialize() + "&template_id=" + $('#current_template_id').val(),
		dataType:   "json",
		success: function(data) {
			var message = _('Save successful');

			$('#msg_viewTemplate').css('color', 'green').text(message).show();
			$('#updatingTemplate').hide();		
						
		}
	}
	);	
}
function showTemplate(event, ui) {
	var templateId = ui.tab.rel;
	getTemplate(templateId);			
}
function getTemplate(templateId) {	
	if (templateId <= 0) return;

	$('#current_template_id').val(templateId);
	
	$.ajax({
		url: "../Surgery/GetTemplateAjax?set_ajax_view",
		data: "template_id=" + templateId,
		success: function(data) {
			
			$('#surgeryTeamTemplateItems').html(data);
			
		}
	});
}
function validate4AddSurgeryService() {
	$('#statusMessage').html('');
	if (!checkMonth($('#inSurgery_mm'),true,'','#statusMessage')) {
		$('#statusMessage').show();
		return false;
	} 

	if (!checkDay($('#inSurgery_dd'),true,'','#statusMessage')) {
		$('#statusMessage').show();	
		return false;
	}	

	var res 	= 	checkDate($('#inSurgery_yyyy'),
			$('#inSurgery_mm'),
			$('#inSurgery_dd'), true, '', '#statusMessage', false);	

	if(!res){	
		$('#statusMessage').show();
		return false;
	}
	if (validateSelectBox("inputServiceSurgeryList", _("Service not selected yet"), "statusMessage") == false) {
		return false;
	}
	var participants = $("table#surgeryParticipants input[name='personNames[]']");
	if (participants == null || participants.length == 0) {
		showMessage("statusMessage", _('Add Doctor/Technician/Nurse'), 'error');
		return false;
	}
	return true;
}

function submitDeleteInPatientSurgery(ticketId, inpatientSurgeryId) {
	$.ajax({
		type:		"GET",
		url:	"../InPatientSurgery/DeleteInPatientSurgeryAjax?set_ajax_view",
		data: 	"ticketId=" + ticketId	+ "&surgeryId=" + inpatientSurgeryId,		
		dataType:   "json",
		success: 	function(data) {			
		if (data.error.code == 0) {
			var serviceType = $('#catergoryId').val();
			displayForm4InputService(ticketId, serviceType);

		} else {
			displayError(data.error.mess);				
		}

	}
	});	
}

function deleteInPatientSurgery(ticketId, inpatientSurgeryId) {
	promptConfirm(_("Delete"),_("Are you sure to delete this surgery?"), function() {
		submitDeleteInPatientSurgery(ticketId, inpatientSurgeryId); 
			return true;
		},'YesNo','warn',_('No'));
}


var countSurgeon = $('tr').filter('#surgeon').length;
var countAnesthesiologist = $('tr').filter('#anesthesiologist').length;
var countNurse = $('tr').filter('#nurse').length;
var startIndex = $('table#surgeryParticipants tr').length;

function isExistent(name,role){
	var len = $("table#surgeryParticipants input[name='personNames[]']").length;
	for(var i=0; i < len; i++){
		var objName	=	$("table#surgeryParticipants input[name='personNames[]']").get(i);
		var objRole	=	$("table#surgeryParticipants input[name='roles[]']").get(i);
		if(objName.value==name && objRole.value==role){
			return true;
		}		
		
	}
	return false;
}
function addParticipant(){
	var row	      = null;
	var name      = '';
	var personId = null;
	
	if ( $('#selectPeople option:selected').val() == '' ) {
		$('#selectPeople option:selected').css("border-color", "red");
 		showMessage("statusMessage", _('Select Doctor/Technician/Nurse'), 'error');
 		return;
	}
	
	name = $('#selectPeople option:selected').text();
	personId = $('#selectPeople option:selected').val();
	
	if (name.length == 0) {
		return;
	}
	
	var role      = $('#surgicalRole :selected').val();
	var roleName  = $('#surgicalRole :selected').attr('label');
	if(isExistent(personId,role)){
		showMessage("statusMessage", _('Duplicated Doctor/Technician and Role'), 'error');
		return;
	}
	$.ajax ({
		type: 	 "POST",
		url:	 "../Surgery/validateEmployeeAjax?set_ajax_view",
		data:	 "name=" + name,
		success: function(data) {
			if (data == 'true') {
				row	=	"<tr id='" + role +"'>"
					+	"<td class='first'><span>" + name + "</span><input type='text' name='personNames[]' id='personNames' value='" + personId + "' style='width: 140px; display: none'/></td>"
					+	"<td><span>" + roleName + "</span><input type='text' name='roles[]' id='roles' value='" + role + "' style='width: 140px; display: none'/></td>"
					+	"<td class='action'><a id='p_row_" + startIndex + "' href=\"javascript:removeRole('p_row_" + startIndex + "')\"><img class='imgBtn' src='../images/remove_small.png' border='0' title='" + _("Delete") + "'/></a></td>"
					+	"</tr>";
				$('table#surgeryParticipants').append(row);
			
				switch(role) {
					case 'surgeon':
			  			countSurgeon++;
			  			break;
			  		case 'anesthesiologist':
			  		    countAnesthesiologist++;
			  		    break;
			  		case 'nurse':
			  			countNurse++;
			  			break;
					default:
			  			break;
				}
				startIndex++;		
				
				$('#personName').val('');
				$('#personName').focus();
				
			} else {
				showMessage("statusMessage", _("This doctor isn't in the list"), 'error');
				
			}
		}
	});
}

function addParticipantFromTemplate(role, roleName, name, personId){
	var row	      = null;
	
	if(isExistent(name,role)){
		$('span#statusMessage').text(_('Duplicated Doctor/Technician and Role')).show();
		return;
	}
	
	row	=	"<tr id='" + role +"'>"
	+	"<td><span>" + name + "</span><input type='text' name='personNames[]' id='personNames' value='" + personId + "' style='width: 140px; display: none'/></td>"
	+	"<td><span>" + roleName + "</span><input type='text' name='roles[]' id='roles' value='" + role + "' style='width: 140px; display: none'/></td>"
	+	"<td class='action'><a id='p_row_" + startIndex + "' href=\"javascript:removeRole('p_row_" + startIndex + "')\"><img class='imgBtn' src='../images/remove_small.png' border='0' title='" + _("Delete") + "'/></a></td>"
	+	"</tr>";
	
	$('table#surgeryParticipants').append(row);
	switch(role) {
		case 'surgeon':
				countSurgeon++;
				break;
			case 'anesthesiologist':
			    countAnesthesiologist++;
			    break;
			case 'nurse':
				countNurse++;
				break;
		default:
				break;
	}
	startIndex++;		
	
	$('#personName').val('');
	$('#personName').focus();
	
}

function removeRole(id) {
	var thisRole = $('#' + id).parent().parent().attr('id');
	switch(thisRole) {
		case 'surgeon':
			countSurgeon--;
			break;    
		case 'anesthesiologist':
			countAnesthesiologist--;
			break;
		case 'nurse':
			countNurse--;
			break;
		default:
			break;
	}
	$('#' + id).parent().parent().remove();
}


function checkParticipant() {
	if (countSurgeon == 0) {
		$('span#statusMessage').text(_('Surgeon is unvailable')).show();
		return false;
	}
	if (countAnesthesiologist == 0) {
		$('span#statusMessage').text(_('Anaesthetist is unvailable')).show();
		return false;
	}
	
	return true;
}



function getUsersByEmployeeType(){
	var employee_type_id = $('#surgicalRole option:selected').val();
	$.ajax({
		type:	"GET",
		url:	"../Surgery/GetUserByEmployeeTypeAjax?set_ajax_view",
		data:	"employee_type_id=" + employee_type_id ,
		beforeSend: function() {
			$('#addPartToList').hide();
		},
		complete: function() {
			$('#addPartToList').show();
		},
		success: function(data){
			$('#selectPeople').html('');
			$('#selectPeople').append("<option id='' value=''>-- " + _("Select employee") + " --</option>");
			$('#selectPeople').append(data);
		}
	});
}

function getUsersByEmployeeTypeForTemplate(roleId, employeeId, personId){
	var employee_type_id = $('#' + roleId + ' option:selected').val();
	if (employee_type_id == '') {
		return;
	}
	
	$.ajax({
		type:	"GET",
		url:	"../Surgery/GetUserByEmployeeTypeAjax?set_ajax_view",
		data:	"employee_type_id=" + employee_type_id ,
		success: function(data){
			$('#' + employeeId).html('');
			$('#' + employeeId).append("<option id='' value=''>-- " + _("Select employee") + " --</option>");
			$('#' + employeeId).append(data);
			
			//Select person with personId
			$('#' + employeeId).children().each(function(){
				if ($(this).val() == personId) {
					$(this).attr('selected', 'selected');
					return false;
				}
				
			});
		}
	});
}

